package org.lord.slark.numbers.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.lord.slark.numbers.R;
import org.lord.slark.numbers.db.LocalDB;
import org.lord.slark.numbers.entity.Scripture;
import org.lord.slark.numbers.utils.BibleTools;
import org.lord.slark.numbers.utils.ELog;
import org.lord.slark.numbers.utils.LocalConstants;

import java.util.List;
import java.util.Random;

public class SplashActivity extends Activity {
    private boolean isInitializeFinished = false;
    private boolean isTimeOver = false;
    private int MSG_INITIALIZE_FINISHED = 1;
    private List<Scripture> scriptureList;
    private TextView tvbible, tvorigin;
    private ImageView imgspinner;
    private Animation rotateAnim;
    private SharedPreferences mSp;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ELog.d("xusai", "initialize finished, waiting for 5s...");
            if (msg.what == MSG_INITIALIZE_FINISHED && isTimeOver) {
                jumpToMainActivity();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splash_layout);

        mSp = getSharedPreferences(LocalConstants.SP_NAME, Context.MODE_PRIVATE);
        tvbible = (TextView)findViewById(R.id.tvbible);
        tvorigin = (TextView) findViewById(R.id.tvorigin);
        imgspinner = (ImageView) findViewById(R.id.imgspinner);
        rotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        LinearInterpolator lp = new LinearInterpolator();
        rotateAnim.setInterpolator(lp);
        MobclickAgent.setDebugMode(ELog.DEBUG);
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        new Thread() {

            @Override
            public void run() {
                SQLiteDatabase db = LocalDB.getInstance(SplashActivity.this).getWritableDatabase();
                if (mSp.getLong(LocalConstants.FIRST_START_TIME, 0L) == 0L) {
                    mSp.edit().putLong(LocalConstants.FIRST_START_TIME, SystemClock.uptimeMillis()).commit();
                    try {
                        ELog.d("xsdebug", "start to initialize the DB...");
                        scriptureList = BibleTools.getScriptures(getResources().getAssets().open("bible.xml"));
                        db.beginTransaction();
                        for (final Scripture scripture : scriptureList) {
                            if (scripture.getId() == 1) {
                                showBible(scripture);
                            }
                            String sqlinsert = "insert into " + Scripture.TABLE_NAME + "  values (?, ?, ?);";
                            try {
                                db.execSQL(sqlinsert, new Object[]{scripture.getId(), scripture.getOrigin(), scripture.getContent()});
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        db.setTransactionSuccessful();
                    }catch(Exception e){
                        e.printStackTrace();
                        ELog.e("xsdebug", "get Scriptures failed!");
                    }finally{
                        db.endTransaction();
                        db.close();
                    }
                    ELog.d("xsdebug", "initialize finished...");
                } else {
                    int id = new Random().nextInt(1001);
                    String sqlquery = "select * from " + Scripture.TABLE_NAME + " where "+Scripture.COLUMN_ID+" = " + id + ";";
                    ELog.d("xsdebug", "query sql>"+sqlquery);
                    try {
                        Cursor c = db.rawQuery(sqlquery, null);
                        while (c.moveToNext()) {
                            ELog.d("xsdebug", "query successful...");
                            Scripture scripture = new Scripture();
                            scripture.setId(c.getInt(c.getColumnIndex(Scripture.COLUMN_ID)));
                            scripture.setOrigin(c.getString(c.getColumnIndex(Scripture.COLUMN_ORIGIN)));
                            scripture.setContent(c.getString(c.getColumnIndex(Scripture.COLUMN_CONTENT)));
                            ELog.d("xsdebug", "Scripture to show>>"+scripture.getContent()+"\n"+">>origin:"+scripture.getOrigin());
                            showBible(scripture);
                        }
                        c.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                isInitializeFinished = true;
                mHandler.sendEmptyMessage(MSG_INITIALIZE_FINISHED);
            }
        }.start();
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                isTimeOver = true;
                ELog.d("xusai", "5s passed, waiting for initialize finished...");
                if (isInitializeFinished) {
                    jumpToMainActivity();
                }
            }
        }, 5000);

    }

    /**
     * Called when the activity has detected the user's press of the back
     * key.  The default implementation simply finishes the current activity,
     * but you can override this to do whatever you want.
     */
    @Override
    public void onBackPressed() {
    }

    private void showBible(final Scripture scripture) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                tvbible.setText(scripture.getContent());
                tvorigin.setText(scripture.getOrigin());
            }
        });
    }

    private void jumpToMainActivity() {
        Intent i = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(i);
        SplashActivity.this.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
        imgspinner.startAnimation(rotateAnim);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
        imgspinner.clearAnimation();
        imgspinner.setVisibility(View.INVISIBLE);
    }

    /**
     * Perform any final cleanup before an activity is destroyed.  This can
     * happen either because the activity is finishing (someone called
     * {@link #finish} on it, or because the system is temporarily destroying
     * this instance of the activity to save space.  You can distinguish
     * between these two scenarios with the {@link #isFinishing} method.
     * <p/>
     * <p><em>Note: do not count on this method being called as a place for
     * saving data! For example, if an activity is editing data in a content
     * provider, those edits should be committed in either {@link #onPause} or
     * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
     * free resources like threads that are associated with an activity, so
     * that a destroyed activity does not leave such things around while the
     * rest of its application is still running.  There are situations where
     * the system will simply kill the activity's hosting process without
     * calling this method (or any others) in it, so it should not be used to
     * do things that are intended to remain around after the process goes
     * away.
     * <p/>
     * <p><em>Derived classes must call through to the super class's
     * implementation of this method.  If they do not, an exception will be
     * thrown.</em></p>
     *
     * @see #onPause
     * @see #onStop
     * @see #finish
     * @see #isFinishing
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }
}
